package boot3.ws;

import boot3.pojo.Message;
import boot3.service.MessageService;
import com.alibaba.fastjson.JSON;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/instantMess/{param}")
@Component
public class InstantMessEndPoint {
    private static final Map<String,Session> onLineUser= new ConcurrentHashMap<>();
    private String userId;
    private List<Message> messageByReceiverId;
    private static MessageService messageService;


    @Autowired
    public void setMessageService(MessageService messageService) {
        InstantMessEndPoint.messageService = messageService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("param") String param) throws IOException {
        System.out.println("连接建立message");
        //建立连接的时候从前端获取用户的iD
        userId = param;
        //将已经建立的用户ID以及session 存储在onLineUsers
        onLineUser.put(userId, session);
    }
    //服务器接受到浏览器发送的消息时会调用
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println(message);
        //首先我们将接受到的消息对象化
        Message mess = JSON.parseObject(message, Message.class);
        //获取消息对象中的receiver_id
        String receive_id = mess.getReceiver_id();
        //思路：先存入数据库中，如果在线发送过去，没有在线则不处理
        messageService.setMessage(mess);
        if(onLineUser.containsKey(receive_id)){//如果在线的话将消息发送过去
            //消息中接受方是否在线，设置
            mess.setOnline(true);
            onLineUser.get(receive_id).getBasicRemote().sendText(JSON.toJSONString(mess));
        }

    }
    @OnClose
    public void onClose(Session session) {
        //关闭时从实时在线表中将用户移除
        onLineUser.remove(userId);
        System.out.println("连接关闭");
    }
    //获取当前的时间
    private String getTime(){
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return dateFormat.format(calendar.getTime());
    }
}
